package com.lcj.odr.controller;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.IdUtil;
import com.alibaba.fastjson.JSONObject;
import com.lcj.common.util.PageUtils;
import com.lcj.common.util.Result;
import com.lcj.odr.controller.form.*;
import com.lcj.odr.db.pojo.OrderBillEntity;
import com.lcj.odr.db.pojo.OrderEntity;
import com.lcj.odr.service.OrderService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.validation.Valid;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

/**
 * @Author : lcj
 * @create 2022/11/16 15:09
 */
@RestController
@RequestMapping("/order")
@Tag(name = "OrderController", description = "订单模块Web接口")
public class OrderController {

    @Resource
    private OrderService orderService;

    @PostMapping("/searchOrderAndCommentByPage")
    @Operation(summary = "查询订单和评价分页记录")
    public Result searchDriverOrderByPage(@RequestBody @Valid SearchOrderAndCommentByPageForm form) {
        Map param = BeanUtil.beanToMap(form);
        int page = form.getPage();
        int length = form.getLength();
        int start = (page - 1) * length;
        param.put("start", start);
        PageUtils pageUtils = orderService.searchOrderAndCommentByPage(param);
        return Result.ok().put("result", pageUtils);
    }

    @PostMapping("/searchDriverOrderWeekNumber")
    @Operation(summary = "查询司机本周订单数")
    public Result searchDriverOrderWeekNumber(@RequestBody @Valid DriverIdForm form) {
        Long num = orderService.searchOrderWeekNumber(form);
        return Result.ok().put("result", num);
    }

    @PostMapping("/searchDriverOrderTotalNumber")
    @Operation(summary = "查询司机总订单数")
    public Result searchDriverOrderTotalNumber(@RequestBody @Valid DriverIdForm form) {
        Long num = orderService.searchOrderTotalNumber(form);
        return Result.ok().put("result", num);
    }

    @PostMapping("/updateOrderAboutPayment")
    @Operation(summary = "查询订单支付状态")
    public Result updateOrderAboutPayment(@RequestBody @Valid SearchOrderForm form) {
        Map param = BeanUtil.beanToMap(form);
        String result = orderService.updateOrderAboutPayment(param);
        return Result.ok().put("result", result);
    }

    @RequestMapping("/receivePayMessage")
    @Operation(summary = "接收支付费用消息通知")
    public Result receiveMessage(@RequestBody HashMap<String, Object> map) throws Exception {
        Long orderId = MapUtil.getLong(map, "orderId");
        if(orderId==null || map.get("payTime") == null) {
            return Result.error("缺少参数");
        }

        String resultCode = MapUtil.getStr(map, "resultCode");
        if ("SUCCESS".equals(resultCode)) {
            String payId = IdUtil.randomUUID();
            String driverOpenId = orderService.searchOrderDriver(orderId);
            String time = (String) map.get("payTime");
            String payTime = DateUtil.parse(time, "yyyyMMddHHmmss").toString("yyyy-MM-dd HH:mm:ss");

            //修改订单状态、执行分账、发放系统奖励
            orderService.handlePayment(orderId, payId, driverOpenId, payTime);

        }
        return Result.ok().put("msg", "支付成功！");
    }

    @PostMapping("/validCanPayOrder")
    @Operation(summary = "检查订单是否可以支付")
    public Result validCanPayOrder(@RequestBody @Valid ValidCanPayOrderForm form) {
        Map param = BeanUtil.beanToMap(form);
        HashMap map = orderService.validCanPayOrder(param);
        return Result.ok().put("result", map);
    }

    @PostMapping("/updateOrderPrepayId")
    @Operation(summary = "更新预支付订单ID")
    public Result updateOrderPrepayId(@RequestBody @Valid UpdateOrderPrepayIdForm form) {
        Map param = BeanUtil.beanToMap(form);
        int rows = orderService.updateOrderPrepayId(param);
        return Result.ok().put("rows", rows);
    }

    @PostMapping("/searchDriverTodayBusinessData")
    @Operation(summary = "查询司机当天营业数据")
    public Result searchDriverTodayBusinessData(@RequestBody @Valid DriverIdForm form) {
        HashMap result = orderService.searchDriverTodayBusinessData(form.getDriverId());
        return Result.ok().put("result", result);
    }

    /**
     * 添加订单
     * @param form
     * @return 订单ID
     */
    @PostMapping("/insertOrder")
    @Operation(summary = "顾客下单")
    public Result insertOrder(@RequestBody @Valid InsertOrderForm form) {
        //订单UUID和客户ID
        OrderEntity orderEntity = new OrderEntity();
        orderEntity.setUuid(form.getUuid());
        orderEntity.setCustomerId(form.getCustomerId());

        //起点信息
        orderEntity.setStartPlace(form.getStartPlace());
        JSONObject json = new JSONObject();
        json.put("latitude", form.getStartPlaceLatitude());
        json.put("longitude", form.getStartPlaceLongitude());
        orderEntity.setStartPlaceLocation(json.toString());
        //终点信息
        orderEntity.setEndPlace(form.getEndPlace());
        json = new JSONObject();
        json.put("latitude", form.getEndPlaceLatitude());
        json.put("longitude", form.getEndPlaceLongitude());
        orderEntity.setEndPlaceLocation(json.toString());
        //费用信息
        orderEntity.setExpectsMileage(new BigDecimal(form.getExpectsMileage()));
        orderEntity.setExpectsFee(new BigDecimal(form.getExpectsFee()));
        orderEntity.setFavourFee(new BigDecimal(form.getFavourFee()));
        orderEntity.setChargeRuleId(form.getChargeRuleId());
        orderEntity.setCarPlate(form.getCarPlate());
        orderEntity.setCarType(form.getCarType());
        orderEntity.setDate(form.getDate());
        //账单费用信息
        OrderBillEntity billEntity = new OrderBillEntity();
        billEntity.setBaseMileage(form.getBaseMileage());
        billEntity.setBaseMileagePrice(new BigDecimal(form.getBaseMileagePrice()));
        billEntity.setExceedMileagePrice(new BigDecimal(form.getExceedMileagePrice()));
        billEntity.setBaseMinute(form.getBaseMinute());
        billEntity.setExceedMinutePrice(new BigDecimal(form.getExceedMinutePrice()));
        billEntity.setBaseReturnMileage(form.getBaseReturnMileage());
        billEntity.setExceedReturnPrice(new BigDecimal(form.getExceedReturnPrice()));

        String id = orderService.insertOrder(orderEntity, billEntity);
        return Result.ok().put("result", id);
    }

    @PostMapping("/acceptNewOrder")
    @Operation(summary = "司机接单")
    public Result acceptNewOrder(@RequestBody @Valid AcceptNewOrderForm form) {
        String result = orderService.acceptNewOrder(form.getDriverId(), form.getOrderId());
        return Result.ok().put("result", result);
    }

    @PostMapping("/searchDriverExecuteOrder")
    @Operation(summary = "查询司机正在执行的订单记录")
    public Result searchDriverExecuteOrder(@RequestBody @Valid AcceptNewOrderForm form) {
        Map param = BeanUtil.beanToMap(form);
        HashMap map = orderService.searchDriverExecuteOrder(param);
        return Result.ok().put("result", map);
    }

    @PostMapping("/searchOrderStatus")
    @Operation(summary = "查询订单状态")
    public Result searchOrderStatus(@RequestBody @Valid SearchOrderForm form) {
        Map param = BeanUtil.beanToMap(form);
        Integer status = orderService.searchOrderStatus(param);
        return Result.ok().put("result", status);
    }

    @PostMapping("/deleteUnAcceptOrder")
    @Operation(summary = "删除没有司机接单的订单")
    public Result deleteUnAcceptOrder(@RequestBody @Valid SearchOrderForm form) {
        Map param = BeanUtil.beanToMap(form);
        String result = orderService.deleteUnAcceptOrder(param);
        return Result.ok().put("result", result);
    }

    @PostMapping("/searchDriverCurrentOrder")
    @Operation(summary = "查询司机当前订单")
    public Result searchDriverCurrentOrder(@RequestBody @Valid DriverIdForm form) {
        HashMap map = orderService.searchDriverCurrentOrder(form.getDriverId());
        return Result.ok().put("result", map);
    }

    @PostMapping("/hasCustomerCurrentOrder")
    @Operation(summary = "查询乘客是否存在当前的订单")
    public Result hasCustomerCurrentOrder(@RequestBody @Valid CustomerIdForm form) {
        HashMap map = orderService.hasCustomerCurrentOrder(form.getCustomerId());
        return Result.ok().put("result", map);
    }

    @PostMapping("/searchOrderForMoveById")
    @Operation(summary = "查询订单信息用于司乘同显功能")
    public Result searchOrderForMoveById(@RequestBody @Valid SearchOrderForm form) {
        Map param = BeanUtil.beanToMap(form);
        HashMap map = orderService.searchOrderForMoveById(param);
        return Result.ok().put("result", map);
    }

    @PostMapping("/arriveStartPlace")
    @Operation(summary = "司机到达上车点")
    public Result arriveStartPlace(@RequestBody @Valid ArriveStartPlaceForm form) {
        Map param = BeanUtil.beanToMap(form);
        param.put("status", 3);
        int rows = orderService.arriveStartPlace(param);
        return Result.ok().put("rows", rows);
    }

    @PostMapping("/confirmArriveStartPlace")
    @Operation(summary = "乘客确认司机到达上车点")
    public Result confirmArriveStartPlace(@RequestBody @Valid SearchOrderForm form) {
        boolean result = orderService.confirmArriveStartPlace(form.getOrderId());
        return Result.ok().put("result", result);
    }

    @PostMapping("/startDriving")
    @Operation(summary = "开始代驾")
    public Result startDriving(@RequestBody @Valid OrderDriverForm form) {
        Map param = BeanUtil.beanToMap(form);
        param.put("status", 4);
        int rows = orderService.startDriving(param);
        return Result.ok().put("rows", rows);
    }

    @PostMapping("/updateOrderStatus")
    @Operation(summary = "更新订单状态")
    public Result updateOrderStatus(@RequestBody @Valid UpdateOrderStatusForm form) {
        Map param = BeanUtil.beanToMap(form);
        int rows = orderService.updateOrderStatus(param);
        return Result.ok().put("rows", rows);
    }

    @PostMapping("/searchOrderByPage")
    @Operation(summary = "查询订单分页记录")
    public Result searchOrderByPage(@RequestBody @Valid SearchOrderByPageForm form) {
        Map param = BeanUtil.beanToMap(form);
        int page = form.getPage();
        int length = form.getLength();
        int start = (page - 1) * length;
        param.put("start", start);
        PageUtils pageUtils = orderService.searchOrderByPage(param);
        return Result.ok().put("result", pageUtils);
    }

    @PostMapping("/searchOrderContent")
    @Operation(summary = "查询订单详情")
    public Result searchOrderContent(@RequestBody @Valid SearchOrderForm form) {
        Map map = orderService.searchOrderContent(form.getOrderId());
        return Result.ok().put("result", map);
    }

    @PostMapping("/searchOrderStartLocationIn30Days")
    @Operation(summary = "查询30天以内订单上车点定位")
    public Result searchOrderStartLocationIn30Days() {
        ArrayList<HashMap> result = orderService.searchOrderStartLocationIn30Days();
        return Result.ok().put("result", result);
    }

    @PostMapping("/validDriverOwnOrderAndGetInfo")
    @Operation(summary = "查询司机是否关联某订单和获取订单信息")
    public Result validDriverOwnOrder(@RequestBody @Valid SearchOrderForm form) {
        if(form.getDriverId() == null) {
            return Result.error("driverId不能为空");
        }
        JSONObject orderInfo = new JSONObject();
        JSONObject resJson = new JSONObject();
        Map param = BeanUtil.beanToMap(form);
        //校验订单是否属于该司机
        boolean bool = orderService.validDriverOwnOrder(param);
        resJson.put("valid", bool);
        //如果属于该司机，获取订单信息
        if(bool) {
            HashMap map = orderService.searchSettlementNeedData(form.getOrderId());
            orderInfo.putAll(map);
            resJson.put("orderInfo", orderInfo);
        }
        return Result.ok().put("result", resJson);
    }

    @PostMapping("/searchSettlementNeedData")
    @Operation(summary = "查询订单的开始和等时")
    public Result searchSettlementNeedData(@RequestBody @Valid SearchOrderForm form) {
        HashMap map = orderService.searchSettlementNeedData(form.getOrderId());
        return Result.ok().put("result", map);
    }

    @PostMapping("/searchOrderById")
    @Operation(summary = "根据ID查询订单和账单信息")
    public Result searchOrderById(@RequestBody @Valid SearchOrderForm form) {
        Map param = BeanUtil.beanToMap(form);
        HashMap map = orderService.searchOrderById(param);
        return Result.ok().put("result", map);
    }
}
